package com.haixee.parkdemo.common.response;

import com.haixee.parkdemo.common.context.WebContextHolder;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author RUIFENG GUO
 * 2020/4/11 16:31
 */
@Slf4j
public class LogUtil {

    private static final String HEADER_USER_AGENT = "user-agent";


    public static CommonLog makeHttpLog(HttpServletRequest request, ResResult commonRes) {

        CommonLog resLog = makeBasicLog(request);

        resLog.setCode(commonRes.getCode());
        resLog.setMsg(commonRes.getMsg());

        return resLog;
    }

    public static CommonLog makeBasicLog(HttpServletRequest request) {

        CommonLog resLog = new CommonLog();

        String ip = RequestUtil.getIp(request);
        WebContextHolder.setIp(ip);

        resLog.setIp(ip);
        resLog.setUserAgent(request.getHeader(HEADER_USER_AGENT));
        resLog.setProto(request.getProtocol());
        resLog.setMethod(request.getMethod());
        resLog.setUrl(request.getRequestURI());
        resLog.setTime(new Date());

        return resLog;
    }

//    public static void saveResInfo(ResultPort resultPort) {
//
//        CommonLog commonLog = WebContextHolder.getLogData();
//        commonLog.setCode(resultPort.getCode());
//        commonLog.setMsg(resultPort.getMsg());
//    }
//
//    public static void saveResInfo(ResResult commonRes) {
//
//        CommonLog commonLog = WebContextHolder.getLogData();
//        commonLog.setCode(commonRes.getCode());
//        commonLog.setMsg(commonRes.getMsg());
//    }

    public static void printLog(HttpServletRequest request, double latency, long startTime) {

        Integer code = WebContextHolder.getResponseCode();
        if (Integer.valueOf(0).equals(code)) {
            log.info("HTTP LOG: " + printString(request, latency, startTime));
        } else {
            log.error("HTTP LOG: " + printString(request, latency,startTime));
        }
    }

    public static void printLog(CommonLog commonLog, String other) {

        if (Integer.valueOf(0).equals(commonLog.getCode())) {
            log.info("HTTP LOG: " + commonLog + ", " + other);
        } else {
            log.error("HTTP LOG: " + commonLog + ", " + other);
        }
    }

    private static String printString(HttpServletRequest request, double latency, long startTime) {
        return "uid=" + WebContextHolder.getUid() + ", proto=" + request.getProtocol() + ", ip=" + WebContextHolder.getIp() + ", latency=" + latency+ ", method=" + request.getMethod() + ", url=" + request.getRequestURI() + ", code=" + WebContextHolder.getResponseCode() + ", msg=" + WebContextHolder.getResponseMsg() + ", userAgent=" + request.getHeader("User-Agent") + ", time=" + new Date(startTime);
    }
}
